package com.biz.primus.ms.tms.specification;

import com.biz.primus.model.tms.enums.DeliveryOrderStatus;
import com.biz.primus.model.tms.vo.DeliverySearchReqVo;
import com.biz.primus.ms.tms.dao.po.DeliveryOrderPo;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * DeliveryOrderPageSpecification
 *
 * @author JKLiues
 * @date 2017年11月23日
 */
@AllArgsConstructor
public class DeliveryOrderPageSpecification implements Specification<DeliveryOrderPo> {
    private DeliverySearchReqVo reqVo;

    @Override
    public Predicate toPredicate(Root<DeliveryOrderPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();
        String orderCode = reqVo.getOrderCode();
        String deliveryCode = reqVo.getDeliveryCode();
        DeliveryOrderStatus deliveryStatus = reqVo.getDeliveryStatus();
        String depotCode = reqVo.getDepotCode();
        if (StringUtils.isNotBlank(deliveryCode)) {
            predicates.add(cb.equal(root.get("deliveryCode").as(String.class), deliveryCode));
        }
        if (StringUtils.isNotBlank(depotCode)) {
            predicates.add(cb.equal(root.get("depotCode").as(String.class), depotCode));
        }
        if (StringUtils.isNotBlank(orderCode)) {
            predicates.add(cb.equal(root.get("orderCode").as(String.class), orderCode));
        }
        if (deliveryStatus != null) {
            predicates.add(cb.equal(root.get("deliveryStatus").as(DeliveryOrderStatus.class), deliveryStatus));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}